import os
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect, render
import json

from blog_analysis.models import Meta, Article
from blog_analysis.service import UserService, TimeRankService, CategoryService
from dataProcess.InfluenceStatistical import InfluenceStatistical
from dataProcess.SomeoneStatistical import SomeoneStatistical
from dataProcess.ThreedAccelerateLaborStatiscal import ThreedAccelerateLaborStatiscal
from dataProcess.TitleStatistical import TitleStatistical
from dataProcess.TopicStatistical import TopicStatistical


# Create your views here.
def index(request):
    return render(request, 'static/index.html')


def login(request):  # 1、登录验证
    username = request.GET.get('username')
    password = request.GET.get('password')

    return HttpResponse(UserService().login(username, password), content_type="application/json")


def register(request):  # 2、注册用户
    # 获取前端传递过来的数据
    username = request.GET.get('username')
    password = request.GET.get('password')
    user_picture = request.GET.get('user_picture')
    types = request.GET.get('type')

    return HttpResponse(UserService().register(username, password, user_picture, types),
                        content_type="application/json")


def timeRank(request):  # 3、文章的时间分布（饼图和柱状图）
    timeRankService = TimeRankService()
    backjson = timeRankService.getTimeRank()
    return HttpResponse(backjson, content_type="application/json")


def category(request):  # 4、文章的类别分布（饼图和柱状图）
    categoryService = CategoryService()
    backjson = categoryService.getCategory()
    return HttpResponse(backjson, content_type="application/json")


def title(request):  # 5、文章的主题分布
    ts = TitleStatistical()
    data = ts.statistical()
    meta = Meta("获取数据集合成功", 200)
    metaFailed = Meta("获取数据集合失败", 400)

    response = {
        'data': data,
        'meta': meta if data is not None else metaFailed
    }
    json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (Article, Meta)) else None,
                          ensure_ascii=True)
    # print(json_str)

    return HttpResponse(json_str, content_type="application/json")


def topic(request):  # 6、时下的热门话题分布分析（）
    ts = TopicStatistical()
    data = ts.statistical()
    meta = Meta("获取数据集合成功", 200)
    metaFailed = Meta("获取数据集合失败", 400)

    response = {
        'data': data,
        'meta': meta if data is not None else metaFailed
    }
    json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (Article, Meta)) else None,
                          ensure_ascii=True)
    # print(json_str)

    return HttpResponse(json_str, content_type="application/json")


def interact(request):  # 7、文章互动分析-----散点图
    return HttpResponse('欢迎测试')


def influence(request):  # 8、文章影响力分析----散点图
    # 直接查询所以商品记录
    influenceStatistical = InfluenceStatistical()
    data = influenceStatistical.statistical()
    meta = Meta("获取数据集合成功", 200)
    metaFailed = Meta("获取数据集合失败", 400)

    response = {
        'data': data,
        'meta': meta if data is not None else metaFailed
    }
    json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (Article, Meta)) else None,
                          ensure_ascii=True)
    # print(json_str)

    return HttpResponse(json_str, content_type="application/json")


def someone(request):  # 9、简单爬取展示 目标用户信息
    # 直接查询所以商品记录
    someoneStatistical = SomeoneStatistical()
    data = someoneStatistical.run()
    meta = Meta("获取数据集合成功", 200)
    metaFailed = Meta("获取数据集合失败", 400)

    response = {
        'data': data,
        'meta': meta if data is not None else metaFailed
    }
    json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (Article, Meta)) else None,
                          ensure_ascii=True)
    # print(json_str)

    return HttpResponse(json_str, content_type="application/json")


def laborRank(request):  # 10、创作者文章数排行
    # 直接查询所以商品记录
    threedAccelerateLaborStatiscal = ThreedAccelerateLaborStatiscal()
    data = threedAccelerateLaborStatiscal.run()
    meta = Meta("获取数据集合成功", 200)
    metaFailed = Meta("获取数据集合失败", 400)

    response = {
        'data': data,
        'meta': meta if data is not None else metaFailed
    }
    json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, (Article, Meta)) else None,
                          ensure_ascii=True)
    # print(json_str)

    return HttpResponse(json_str, content_type="application/json")


# 11、 上传用户头像 http://127.0.0.1:8888/static/picture/xXxX.jpg
def UserPicture(request):
    if request.method == 'POST':
        fileName = request.FILES.get('file').name
        # 当前脚本的绝对路径
        my_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        upload_path = my_BASE_DIR + '/static/picture/' + fileName

        fileData = request.FILES.get('file').read()
        with open(upload_path, "wb+") as f:
            f.write(fileData)

    # do something else with the image if needed
    response = {
        'img': "http://127.0.0.1:8888/static/picture/" + fileName
    }
    json_str = json.dumps(response, default=lambda o: o.__json__() if isinstance(o, str) else None,
                          ensure_ascii=False)
    return HttpResponse(json_str, content_type="application/json")
